from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from meiduo_admin.utils import MyPageNumberPagination
from .brands_serializers import GoodsBrandsSerializers
from goods.models import Brand
from fdfs_client.client import Fdfs_client
from django.conf import settings


class GoodsBrandsView(ModelViewSet):
    pagination_class = MyPageNumberPagination
    serializer_class = GoodsBrandsSerializers
    queryset = Brand.objects.order_by("id").all()

    # 重写create方法将logo保存到数据库中
    def create(self, request, *args, **kwargs):
        # 1,获取参数
        logo = request.FILES.get("logo")
        name = request.data.get("name")
        first_letter = request.data.get("first_letter")

        # 2,校验参数
        if not all([logo, name, first_letter]):
            return Response(status=403)

        # 3,数据入库
        client = Fdfs_client(settings.FDFS_CONFIG)
        ret = client.upload_by_buffer(logo.read())

        # 3,1判断是否成功
        if ret["Status"] != "Upload successed.":
            return Response(status=400)

        # 3,2数据入库图片
        image_url = ret.get("Remote file_id")
        Brand.objects.create(logo=image_url, name=name, first_letter=first_letter)

        # 4,返回响应
        return Response(status=201)

    # 重写update方法实现logo修改
    def update(self, request, *args, **kwargs):
        # 1,获取参数
        logo = request.FILES.get("logo")
        name = request.data.get("name")
        first_letter = request.data.get("first_letter")
        instance = self.get_object()

        # 2,校验参数
        if not all([logo, name, first_letter]):
            return Response(status=403)

        # 3,数据入库
        client = Fdfs_client(settings.FDFS_CONFIG)
        ret = client.upload_by_buffer(logo.read())

        # 3,1判断是否成功
        if ret["Status"] != "Upload successed.":
            return Response(status=400)

        # 3,2数据入库图片
        image_url = ret.get("Remote file_id")
        Brand.objects.filter(id=instance.id).update(logo=image_url, name=name, first_letter=first_letter)

        # 4,返回响应
        return Response(status=201)
